package com.zqx.finanl.com.zqx.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class CountDownLatchDemo1 {

    //请求总数
    public static int clientTotal = 1000;
    //同时并发执行的线程数
    public static int threadTotal = 50;
    //方式一
    //public static int count = 0;
    //方式2
    public static AtomicInteger count2 = new AtomicInteger(0);
    public static void main(String[] args) throws Exception{

        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i=0;i<clientTotal;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        //System.out.println("输出结果为："+count);
        System.out.println("输出结果为："+count2);
        log.info("count2={}",count2);
    }

    /**
     * 方式1：因为count++非原子性操作，所以多线程环境下会涉及线程安全问题
     * synchronized 保证了线程安全
     */
    /*private synchronized static void add() {
        count++;
    }*/

    /**
     * 方式2：AtomicInteger保证了原子性
     */
    private static void add(){
        count2.addAndGet(1);
    }
}
